<template>
  <div class="yx-bg">
    <div id="top-panel" style="height: 15rem;">
      <div style="float: left;">
        <img style="width: 4rem; margin-top: 2rem; margin-left: 2rem;" src="/static/img/home.png" @click="returnHome">
        <div style="margin-left: 2rem; color: #FE7F7E;">返回首页</div>
      </div>
      
      <img id="meihua" style="width: 60%; float: right; margin-right: -15%;" src="/static/img/meihua.png">
    </div>

    <div v-show="!isInTimeRange"  style="font-size: 2.5rem; text-align: center;">
      {{tip}}
    </div>

    <div v-show="isInTimeRange" style="font-size: 2.2rem; text-align: center;">当前答对题目数量：<span style="font-size: 2.5rem; font-weight: bold; color: red;">{{userAnswerCorrectNum}}</span></div>


    <div v-show="isInTimeRange" style="text-align: center; font-size: 3.5rem; margin-top: 3rem">
      {{question}}
    </div>

    <div v-show="isInTimeRange" style="margin-top: 3rem;">
      <div style="display: flex; align-items: center; width: 25rem; margin: 0 auto;">
        <input style="width: 20rem; height: 4rem; border: none; border-radius: 5px; font-size: 2.2rem; z-index: 9990" v-model="answer" placeholder="请输入答案">
      <img :src="judgeIcon" v-show="showJudgeIcon" style="width: 4rem; margin-left: -4rem; z-index: 9991">
      <button type="button" class="btn btn-danger" style="font-size: 2rem; width: 8rem; z-index: 9990" @click="submitAnswer" :disabled="disabled">确认</button>
      </div>
      
    </div>

    <!-- <div v-show="showJudgeIcon" style="text-align: center; font-size: 2.2rem; margin-top: 2rem;">
      正确答案：{{correctAnswer}}
    </div> -->

    <div v-show="isInTimeRange" style="text-align: center; margin-top: 2rem;">
      <button type="button" class="btn btn-primary" style="font-size: 2.2rem; width: 10rem;" @click="nextQuestion">下一题</button>
    </div>

    <div v-show="firstCorrectUserId==0&&isInTimeRange" style="text-align: center; font-size: 1.6rem; font-weight: 600; margin-top: 2rem;">此题当前没人回答正确！快快抢答赢大奖！</div>

    <button v-show="false" type="button" class="btn btn-primary" style="font-size: 2.2rem; width: 10rem;" @click="clearLocalStorage">清空localStorage</button>
    <!-- <div > -->
    <div v-show="firstCorrectUserId!=0&&isInTimeRange" style="width: 100%; display: flex; align-items: center; font-size: 1.8rem; margin-top: 2rem;">
      <div style="width: 40%; text-align: right;">首次答对用户：</div>
      <div style="width: 60%;">
        <img :src="firstCorrectUser.head_img_url" style="width: 5rem; border-radius: 50%;">
        <span style="color: red; font-weight: bold;">{{firstCorrectUser.nick_name}}</span>
      </div>
      
    </div>

    <!-- <div id="footer-panel">
      <div style="position: relative;">
        <img id="mudan2" style="width: 30%; position: absolute; right: 0; bottom: 0; z-index: 100" src="/static/img/mudan2.png">
        <img id="mudan1" style="width: 30%; position: absolute; right: 23%; bottom: -10%; z-index: 101" src="/static/img/mudan1.png">
        <img id="footer-chengqiang" src="/static/img/chengqiang.png">
      </div>
    </div> -->

    <div id="footer-panel">
      <img src="/static/img/logo.png" style="width: 20%;">
      <span style="font-size: 1.3rem; font-weight: 600;">六六电竞提供技术支持</span>
      <div style="height: 2rem"></div>
    </div>

    <div v-show="showPanel" style="position: absolute; width: 100%; height: 100%; top: 0; background-color: rgba(0,0,0, 0.5); z-index: 9999">
      <div id="first_blood_panel" style="width: 80%; margin-left: 10%; padding: 3rem 3rem; background-color: #ffffff; margin-top: 15rem; border-radius: 1rem; font-size: 2rem; color: red;">
        <div>
          你已经答对了{{first_blood_count}}道无人答对的题目，快点去朋友圈晒出成绩，领取大奖！
        </div>
        <div style="width: 100%; text-align: center; margin-top: 2rem;">
          <button type="button" class="btn btn-danger" style="font-size: 2.3rem;" @click="closeFirstBloodPanel">关闭</button>
        </div>
      </div>
    </div>
    
  </div>


</template>
<script>
import wx from 'weixin-js-sdk'

export default {
  data () {
    return {
      questionId: 0,
      question: "",
      answer: "",
      judgeIcon: "/static/img/correct.png",
      showJudgeIcon: false,
      disabled: false,
      firstCorrectUserId: 0,
      firstCorrectUser: {},
      currentCorrectNum: 0,
      showPanel: false,
      userAnswerCorrectNum: 0,
      first_blood_count: 0,
      isInTimeRange: false,
      tip: "hahahhahah",
    }
  },
  mounted: function() {

    // TweenLite.from("#denglong", 1, {
    //   y: "-400",
    //   opacity: 0,
    // })

    TweenLite.from("#meihua", 1, {
      x: "+400",
      opacity: 0,
    })

    // TweenLite.from("#footer-chengqiang", 2, {
    //   y: "+400",
    //   opacity: 0,
    // })

    // TweenLite.from("#mudan1", 1.3, {
    //   y: "+400",
    //   opacity: 0,
    // })

    // TweenLite.from("#mudan2", 1, {
    //   y: "+400",
    //   opacity: 0,
    // })

    if (!localStorage.getItem('openid') || localStorage.getItem('openid') == "undefined") {
      window.location = 'http://www.66nmgame.com/yuanxiao.html'
    }

    this.userAnswerCorrectNum = parseInt(localStorage.getItem('answer_correct_num'))

    this.verifyTimeRange()

    this.getQuestion()
    
  },
  methods: {

    clearLocalStorage: function() {
      localStorage.clear()
    },

      getQuestion: function() {
        let openid = localStorage.getItem('openid')
        this.$axios.get(`/getRandomYuanXiaoQuestion.php?openid=${openid}`)
        .then(res => {
          console.log(res.data)
          this.question = res.data.question
          this.questionId = res.data.id
          this.firstCorrectUserId = res.data.first_correct_user_id
          if (this.firstCorrectUserId != 0 && res.data.first_correct_user) {
            this.firstCorrectUser = res.data.first_correct_user
          }
          this.currentCorrectNum = res.data.current_correct_num
        })
      },

      submitAnswer: function() {

        if (this.answer == "") {
          return
        }

        let userId = localStorage.getItem('user_id')

        let that = this
        this.$axios.get(`/answerYuanXiaoQuestion.php?user_id=${userId}&question_id=${this.questionId}&answer=${this.answer}`)
        .then(res => {

          // alert(`code==${res.data.code}---errmsg==${res.data.errmsg}---first_blood==${res.data.first_blood}---user_id=${userId}`)

          console.log(res.data)
          if (res.data.code == 1) {
            // 回答正确
            that.judgeIcon = "/static/img/correct.png"
            that.disabled = true

            if (res.data.first_blood == 1) {
              // that.getSignPackage()
              that.first_blood_count = res.data.first_blood_count
              that.changeWxConfig()
              that.showFirstBloodPanel()
            } else {
              setTimeout(function() {
                that.nextQuestion()
              }, 1000)
            }

            that.userAnswerCorrectNum = that.userAnswerCorrectNum + 1
            localStorage.setItem('answer_correct_num', that.userAnswerCorrectNum)
            
          } else {
            // 回答错误
            that.judgeIcon = "/static/img/error.png"
          }
          that.showJudgeIcon = true
        })

      },

      nextQuestion: function() {
        this.questionId = 0,
        this.question = "",
        this.answer = "",
        this.showJudgeIcon = false,
        this.disabled = false,
        this.firstCorrectUserId = 0,
        this.firstCorrectUser = {},
        this.currentCorrectNum = 0,
        this.getQuestion()
        this.resetWxConfig()
      },

      showFirstBloodPanel() {
        this.showPanel = true
        this.showFirstBloodPanelAnimation()
      },

      showFirstBloodPanelAnimation() {
        TweenLite.from("#first_blood_panel", 0.5, {
          scale: 0,
        })
      },

      closeFirstBloodPanel() {
        this.showPanel = false
      },

      returnHome: function() {
        this.$router.push({path: 'cover'})
      },

    //   getSignPackage: function() {
    //   let currentUrl = window.location.href
    //   let urlArr = currentUrl.split("#")
    //   let url = encodeURIComponent(urlArr[0])
    //   // alert(currentUrl)
    //   // alert(url)
    //   this.$axios.get(`getAccess.php?url=${url}`)
    //         .then(res => {
    //           console.log("getAccess==========================")
    //           console.log(res)
    //           this.setWxConfig(res.data)
    //         })
    //         .catch(error => {
    //           console.log(error)
    //         })
    // },
    // setWxConfig: function(data) {
    //   let questionId = this.questionId
    //   let question = this.question
    //   wx.config({
    //       debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    //       appId: data.appId, // 必填，公众号的唯一标识
    //       timestamp: data.timestamp, // 必填，生成签名的时间戳
    //       nonceStr: data.nonceStr, // 必填，生成签名的随机串
    //       signature: data.signature,// 必填，签名
    //       jsApiList: [
    //         'onMenuShareTimeline',
    //         // 'updateAppMessageShareData',
    //         'onMenuShareAppMessage'
    //       ] // 必填，需要使用的JS接口列表
    //   });
    //   wx.ready(function() {
    //     console.log('接口配置信息已经完成')
        
    //     wx.onMenuShareTimeline({
    //       title: `我是第一个答对${questionId}、${question}的人，快来一起抢答赢大奖！`,
    //       link: 'http://www.66nmgame.com/yuanxiao.html',
    //       imgUrl: 'http://www.66nmgame.com/static/img/share.png',
    //       success: function() {
    //         console.log('用户点击按钮回调')
    //         // hideShareTemp()
    //       }
    //     })

    //     wx.onMenuShareAppMessage({
    //       title: `我是第一个答对${questionId}、${question}的人，快来一起抢答赢大奖！`,
    //       desc: "元宵灯谜活动！",
    //       link: 'http://www.66nmgame.com/yuanxiao.html',
    //       imgUrl: 'http://www.66nmgame.com/static/img/share.png',
    //       success: function() {
    //         console.log("分享给朋友设置成功!")
    //       }
    //     })
    //   })
    // },


    changeWxConfig: function() {

      let questionId = this.questionId
      let question = this.question
      let first_blood_count = this.first_blood_count
      let percent = this.getPercent(first_blood_count)
      let that = this

      wx.ready(function() {

        wx.onMenuShareTimeline({
          title: `我已经消灭了${first_blood_count}道无人答对的题目！超过了${percent}的人！`,
          link: 'http://www.66nmgame.com/yuanxiao.html',
          imgUrl: 'http://www.66nmgame.com/static/img/share.png',
          success: function() {
            console.log('用户点击按钮回调')
            // hideShareTemp()
            that.closeFirstBloodPanel()
          }
        })

        wx.onMenuShareAppMessage({
          title: `猜灯谜，赢大奖`,
          desc: `我已经消灭了${first_blood_count}道无人答对的题目！超过了${percent}的人！`,
          link: 'http://www.66nmgame.com/yuanxiao.html',
          imgUrl: 'http://www.66nmgame.com/static/img/share.png',
          success: function() {
            console.log("分享给朋友设置成功!")
          }
        })

      })
    },

    getPercent: function(first_blood_count) {
      if (first_blood_count == 1) {return "12.5%"} 
      else if (first_blood_count == 2) {return "24.8%"}
      else if (first_blood_count == 3) {return "33.5%"}
      else if (first_blood_count == 4) {return "47.2%"}
      else if (first_blood_count == 5) {return "51.2%"}
      else if (first_blood_count == 6) {return "66.6%"}
      else if (first_blood_count == 7) {return "74.5%"}
      else if (first_blood_count == 8) {return "88.8%"}
      else if (first_blood_count == 9) {return "92.1%"}
      else if (first_blood_count == 10) {return "99.9%"}
      else{return "100%"}
    },


    resetWxConfig: function() {
      wx.ready(function() {
        // console.log('接口配置信息已经完成')
        
        wx.onMenuShareTimeline({
          title: `快来一起闹元宵，猜灯谜，赢大奖！`,
          link: 'http://www.66nmgame.com/yuanxiao.html',
          imgUrl: 'http://www.66nmgame.com/static/img/share.png',
          success: function() {
            console.log('用户点击按钮回调')
            // hideShareTemp()
          }
        })

        wx.onMenuShareAppMessage({
          title: `猜灯谜，赢大奖`,
          desc: "快来一起闹元宵，猜灯谜，赢大奖！",
          link: 'http://www.66nmgame.com/yuanxiao.html',
          imgUrl: 'http://www.66nmgame.com/static/img/share.png',
          success: function() {
            console.log("分享给朋友设置成功!")
          }
        })
      })

    },


    verifyTimeRange: function() {

      var startTime = "2019-02-19 13:00:00"
      var endTime = "2019-02-20 12:00:00"

      let startTimestamp = new Date(Date.parse(startTime.replace(/-/g,"/")))
      let endTimestamp = new Date(Date.parse(endTime.replace(/-/g,"/")))

      let curTimestamp = new Date()

      // console.log("=========log start==========")
      // console.log(startTimestamp)
      // console.log(endTimestamp)
      // console.log(curTimestamp)
      // console.log("=========log end==========")

      if (curTimestamp >= startTimestamp && curTimestamp <= endTimestamp) {
        this.isInTimeRange = true
      } else {
        this.tip = "当前不在活动时间！"
      }

    }




  }
}
</script>
